import { useCallback, useEffect, useState } from "react";

interface Ignore {
  current: boolean;
}

function useData<T = any>(url: string) {
  const [data, setData] = useState<T>();

  /**
   * 异步获取数据
   */
  const getData = useCallback(
    async (ignore: Ignore = { current: true }) => {
      if (url === undefined) {
        return;
      }
      const response = await fetch(url);
      const json = await response.json();
      // 忽略当前请求，避免重复请求
      if (!ignore.current) {
        return;
      }
      setData(json);
    },
    [url]
  );

  /**
   * url变化时重新获取数据
   */
  useEffect(() => {
    const ignore: Ignore = { current: true };
    getData(ignore);

    return () => {
      ignore.current = false;
    };
  }, [getData]);

  return data;
}

export default useData;
